package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import com.tanhua.service.FriendApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author げっしょく
 * @date 2021/10/30
 */
@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //添加好友
    @Override
    public void addFriend(Long userId, Long id) {
        //判断同意人与申请人之间有没有好友关系
        Criteria criteria1 = Criteria.where("userId").is(id).and("friendId").is(userId);
        Query query1 = Query.query(criteria1);
        Friend one = mongoTemplate.findOne(query1, Friend.class);
        if (one == null) {
            Friend friend = new Friend();
            friend.setUserId(id);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //判断申请人和同意人之间有没有好友关系
        Criteria criteria2 = Criteria.where("userId").is(userId).and("friendId").is(id);
        Query query2 = Query.query(criteria2);
        Friend one1 = mongoTemplate.findOne(query2, Friend.class);
        if (one1 == null) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(id);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

    }

    //查询好友列表
    @Override
    public List<Friend> getFriendsId(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query q = Query.query(criteria).skip((page - 1) * pagesize).limit(pagesize);
        List<Friend> friends = mongoTemplate.find(q, Friend.class);
        return friends;
    }

    //删除好友
    @Override
    public void deletFriend(Long userId, Long id) {
        //
        Criteria criteria = Criteria.where("userId").is(id).and("friendId").is(userId);
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, Friend.class);
/*        Friend one = mongoTemplate.findOne(query, Friend.class);
        if (one != null) {
            mongoTemplate.remove(one);
        }*/

        Criteria criteria1 = Criteria.where("userId").is(userId).and("friendId").is(id);
        Query query1 = Query.query(criteria1);
        mongoTemplate.remove(query1, Friend.class);
/*        Friend one1 = mongoTemplate.findOne(query1, Friend.class);
        if (one1 != null) {
            mongoTemplate.remove(one1);
        }*/
    }
}
